package studysystem.demo.controller;

import com.github.pagehelper.PageHelper;
import org.apache.shiro.codec.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import studysystem.demo.bean.Learner;
import studysystem.demo.bean.Course;
import studysystem.demo.mapper.LearnerMapper;
import studysystem.demo.tool.*;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.sql.Timestamp;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
public class LearnerController {

    @Autowired
    private LearnerMapper learnerMapper;

    //注册学习者  测试OK
    @CrossOrigin
    @RequestMapping(value = "/learner/new",method = RequestMethod.POST)
    @ResponseBody
    public Mess addLearner(@RequestBody Learner learnerEntity){
        String b;
        System.out.println("start register:");
        if(learnerEntity.getPhone()==null||!chickPhone(learnerEntity.getPhone())){
            b = "手机号格式错误!";
        }else if (learnerMapper.findLearnerInfo(learnerEntity.getPhone())!=null){
            b = "此手机号已注册!";
        }else if (learnerEntity.getPassword()==null||!chickPassword(learnerEntity.getPassword())){
            b = "密码格式错误!";
        }else if (learnerEntity.getPassword2()==null||!learnerEntity.getPassword().equals(learnerEntity.getPassword2())){
            b = "两次输入的密码不一致!";
        }else if (learnerEntity.getName()==null||!chickName(learnerEntity.getName())){
            b = "姓名格式错误!";
        }else if (learnerEntity.getSex()==null||!chickSex(learnerEntity.getSex())){
            b = "性别填写错误!";
        }else if (learnerEntity.getUserid()==null||!chickUserid(learnerEntity.getUserid())){
            b = "身份证格式错误!";
        }else {
            String salt = learnerEntity.getPhone();
            learnerEntity.setPassword(md5Hex(salt+learnerEntity.getPassword()));
            learnerEntity.setRgsttime(getNtime());
            learnerMapper.saveLearner(learnerEntity);
            /**Role roleEntity = new Role();
            roleEntity.setUsername(learnerEntity.getPhone());
            roleEntity.setRole("3");//--学习者
            //learnerMapper.saveRole(roleEntity);
             **/
            b = "注册成功!";
        }
        System.out.println(b);
        return Mess.info(b);
    }

    //查询所有学习者 兼 搜索 兼 分页
    @CrossOrigin
    @RequestMapping(value="/learner/all", method = RequestMethod.GET)
    @ResponseBody
    public MyResp adminList(
                            @RequestParam(value="value",required = false,defaultValue = "null") String value,
                            @RequestParam(value="type",required = false,defaultValue = "null") String type){
        PageHelper.startPage(1, 10);
        switch (type){
            case "Name":
                return  MyResp.render(0,"获取成功", learnerMapper.findLearnerByName(value), learnerMapper.findLearnerCountByName(value));
            case "phone":
                    return MyResp.render(0,"获取成功", learnerMapper.findLearnerByPhone(value), learnerMapper.findLearnerCountByPhone(value));
            case "":
                return MyResp.render(0,"获取成功", learnerMapper.findLearnerAll(), learnerMapper.findLearnerCountAll());
            default:
                return MyResp.render(0,"获取成功", learnerMapper.findLearnerAll(), learnerMapper.findLearnerCountAll());
        }
    }

    //修改个人信息 测试OK
    @CrossOrigin
    @RequestMapping(value = "/learner/update",method = RequestMethod.PUT)
    @ResponseBody
    public Mess updateLearner(@RequestBody Learner learnerEntity, HttpServletRequest request){
        String b;
        Learner learner =(Learner) request.getSession().getAttribute("user");
        learnerEntity.setPhone(learner.getPhone());
        if (learnerEntity.getName()==null||!chickName(learnerEntity.getName())){
            b = "姓名格式错误!";
        }else if (learnerEntity.getSex()==null||!chickSex(learnerEntity.getSex())){
            b = "性别填写错误!";
        }else if (learnerEntity.getUserid()==null||!chickUserid(learnerEntity.getUserid())){
            b = "身份证格式错误!";
        }else {
            String salt = learnerEntity.getPhone();
            learnerEntity.setPassword(md5Hex(salt+learnerEntity.getPassword()));
            learnerMapper.updateLearner(learnerEntity);
            b = "修改成功!";
        }
        return Mess.info(b);
    }

    //查看个人信息  测试OK
    @CrossOrigin
    @RequestMapping(value = "/learner/info",method = RequestMethod.GET)
    @ResponseBody
    public Learner personalInfo(HttpServletRequest request){
        Learner learner =(Learner) request.getSession().getAttribute("user");
        Learner learner1 = learnerMapper.findLearnerInfo(learner.getPhone());
        if(learnerMapper.findCoursedir(learner.getPhone())==null)
        {
            learner1.setCoursedir("未选择学习方向，请选择！");
        }else{
            learner1.setCoursedir(learnerMapper.findCoursedir(learner.getPhone()));
        }
        return learner1;
    }
    //删除学习者   测试OK
    @CrossOrigin
    @RequestMapping(value = "/learner/delete/{phone}", method = RequestMethod.DELETE)
    @ResponseBody
    public Mess deleteLearner(@PathVariable String phone){
        String b;
        if(phone!=null&& learnerMapper.findLearnerInfo(phone)!=null&&chickPhone(phone)){
            learnerMapper.deleteLearner(phone);
            b = "删除成功!";
        }else {
            b = "删除失败!";
        }
        return Mess.info

                (b);
    }

    //修改密码  测试OK
    @CrossOrigin
    @RequestMapping(value = "/learner/updatepsd",method = RequestMethod.PUT)
    @ResponseBody
    public Mess updatePsd(@RequestBody Learner learnerEntity, HttpServletRequest request){
        String b;
        Learner learner =(Learner) request.getSession().getAttribute("user");
        learnerEntity.setPhone(learner.getPhone());
        if(learnerEntity.getOldpassword()==null||!md5Hex(learnerEntity.getPhone()+learnerEntity.getOldpassword()).equals(learnerMapper.findLearnerPsw(learnerEntity.getPhone()).getPassword())) {
            b = "旧密码错误!";
        }else if (learnerEntity.getPassword()==null||!chickPassword(learnerEntity.getPassword())) {
            b = "新密码格式错误!";
        }else if(learnerEntity.getPassword2()==null||!learnerEntity.getPassword().equals(learnerEntity.getPassword2())){
            b = "两次密码输入不一致!";
        }else {
            learnerEntity.setPassword(md5Hex(learnerEntity.getPhone()+learnerEntity.getPassword()));
            learnerMapper.updatePsw(learnerEntity);
            b = "密码修改成功!";
        }
        return Mess.info(b);
    }

    //选择学习方向 测试OK
    @CrossOrigin
    @RequestMapping(value = "/learner/dir",method = RequestMethod.POST)
    @ResponseBody
    public Mess updateDir(@RequestBody Learner learnerEntity, HttpServletRequest request){
        String b="0";
        Learner learner =(Learner) request.getSession().getAttribute("user");
        learnerEntity.setPhone(learner.getPhone());
        System.out.println(learnerEntity.getCoursedir());
        if (learnerMapper.checkCoursedir(learnerEntity.getCoursedir())==null) {

            b = "不存在该学习方向，请重新选择!";
        }else {
            learnerMapper.updateCoursedir(learner.getPhone(),learnerEntity.getCoursedir());
            b= "您已成功修改学习方向！";
        }
        return Mess.info(b);
    }
    //查询某个学习者 测试OK
    @CrossOrigin
    @RequestMapping(value="/find/learner/{name}", method = RequestMethod.GET)
    @ResponseBody
    public MyResp FindLearner(@PathVariable String name){
        if(learnerMapper.findLearnerByName2(name)==null){
            return MyResp.render(0,"不存在该学习者！", learnerMapper.findLearnerAll(), learnerMapper.findLearnerCountAll());
        }else
            return  MyResp.render(0,"获取成功", learnerMapper.findLearnerByName(name), learnerMapper.findLearnerCountByName(name));
    }

    /**
     * 方法
     * @param src
     * @return
     */

    //加盐密码哈希
    private static String md5Hex(String src) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bs = md5.digest(src.getBytes());
            new Hex();
            return new String(Hex.encode(bs));
        } catch (Exception e) {
            return null;
        }
    }

    //检验手机号
    private boolean chickPhone(String username){
        Pattern pattern = Pattern.compile("^1[345789]\\d{9}$");
        Matcher match=pattern.matcher(username);
        return match.matches();
    }

    //检验密码
    private boolean chickPassword(String password){
        Pattern pattern = Pattern.compile("^[a-zA-Z0-9]{6,15}$");
        Matcher match=pattern.matcher(password);
        return match.matches();
    }

    //检验性别
    private boolean chickSex(String sex){
        Boolean b = false;
        if(sex.equals("男")||sex.equals("女")){
            b = true;
        }
        return b;
    }

    //检验身份证
    private boolean chickUserid(String userid){
        Pattern pattern = Pattern.compile("^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|30|31)|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|X)$");
        Matcher match=pattern.matcher(userid);
        return match.matches();
    }

    //检验姓名
    private boolean chickName(String name){
        Pattern pattern = Pattern.compile("^[\u4e00-\u9fa5]{2,5}$");
        Matcher match=pattern.matcher(name);
        return match.matches();
    }

    //获取当前时间
    private Date getNtime(){
        Date date = new Date();
        return new Timestamp(date.getTime());
    }

}
